import pymysql

conn = pymysql.connect(
    host="127.0.0.1",
    user="root",
    password="",
    port=3306,
    db="db_transaction",
    charset='utf8'
)


def show_datas():
    cursor = conn.cursor()
    cursor.execute("select * from account")
    for data in cursor.fetchall():
        print(data)


# 初始化数据
cursor = conn.cursor()
cursor.execute("""drop table if exists account""")
cursor.execute("""
  create table account
  (
      id    int auto_increment primary key,
      name  varchar(100),
      money int
  ) engine=innodb default char set utf8mb4 ;
""")
cursor.execute("""insert into account(name, money) values ('account_a', 100), ('account_b', 0); """)
conn.commit()

print("事务前数据：")
show_datas()

try:
    cursor = conn.cursor()

    # 账户A减去数据
    cursor.execute("update account set money = money-80 where name = 'account_a'")
    # 正常：账户B，加上数据
    # cursor.execute("update account set money = money+80 where name = 'account_b'")
    # 异常：账户B，加上数据，但是肯定报错
    cursor.execute("update account set money = money+80 where nameaaaaa = 'account_b'")

    # 如果前面没抛异常，提交事务
    print()
    print("事务提交成功")
    conn.commit()

except Exception as e:
    print()
    print("出现异常: ", e)
    # 出现异常，实现回滚操作
    conn.rollback()

print()
print("事务后数据：")
show_datas()

print("over")
